import datetime
from uuid import uuid4

from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.cache import cache
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from rest_framework_jwt.views import ObtainJSONWebToken, jwt_response_payload_handler

from apps.utils.jwt_util import jwt_get_session_id
from apps.utils.request_util import get_request_ip, get_browser, get_os, get_login_location
from utils.response import ErrorResponse, SuccessResponse
from .Serializers import UserProfileSerializer, LoginInferSerializer
from .models import LoginInfer

User = get_user_model()


class LogoutView(APIView):
    queryset = User.objects.all()
    permission_classes = (IsAuthenticated,)
    prefix = settings.JWT_AUTH.get('JWT_AUTH_HEADER_PREFIX', 'JWT')

    def post(self, request, pk=None):
        user = request.user
        user.user_secret = uuid4()
        user.save()
        key = f"{self.prefix}_{user.username}"
        print(key, cache.has_key(key))
        cache.delete(key)
        return SuccessResponse()


class LoginView(ObtainJSONWebToken):
    JWT_AUTH_COOKIE = ''
    prefix = settings.JWT_AUTH.get('JWT_AUTH_HEADER_PREFIX')
    ex = settings.JWT_AUTH.get('JWT_EXPIRATION_DELTA')

    def save_login_infor(self, request, msg='', status=True, session_id=''):
        User = get_user_model()
        instance = LoginInfer()
        instance.session_id = session_id
        instance.browser = get_browser(request)
        instance.ipaddr = get_request_ip(request)
        instance.loginLocation = get_login_location(request)
        instance.msg = msg
        instance.os = get_os(request)
        instance.status = status
        instance.creator = request.user and User.objects.filter(username=request.data.get('username')).first()
        instance.save()

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            user = serializer.object.get('user') or request.user
            token = serializer.object.get("token")
            response_data = jwt_response_payload_handler(token, user, request)
            response = SuccessResponse(response_data)
            if token:
                usernames = user.username
                session_id = jwt_get_session_id(token)
                key = f"{self.prefix}_{session_id}_{usernames}"
                cache.set(key, token, self.ex.total_seconds())
                print(cache.get(key))
                self.save_login_infor(request, '登录成功', session_id=session_id)
            if self.JWT_AUTH_COOKIE and token:
                expiration = (datetime.datetime.utcnow() + self.ex)
                response.set_cookie(self.JWT_AUTH_COOKIE,
                                    token,
                                    expires=expiration,
                                    domain=settings.SESSION_COOKIE_DOMAIN,
                                    httponly=False)
            return response
        self.save_login_infor(request, '登录失败，账户/密码不正确', False)
        return ErrorResponse(data=serializer.errors, msg="账户/密码不正确")


class GetUserProfileView(APIView):
    def get(self, request, form=None):
        print(request.user)
        user_dict = UserProfileSerializer(request.user).data
        print(user_dict)
        delete_cache = request.user.delete_cache
        return SuccessResponse({
            # 'permissions': [ele for ele in permissions_list if ele],
            # 'roles': Role.objects.filter(userprofile=request.user).values_list('roleKey', flat=True),
            'user': user_dict
        })


class GetUserLoginView(APIView):
    def get(self, request, form=None):
        user_login_dict = LoginInferSerializer(request.user).data
        delete_cache = request.user.delete_cache
        return SuccessResponse({
            "user_login_dict": user_login_dict
        })
